package com.itheima.health.controller;

/**
 * @author ：seanyang
 * @date ：Created in 2019/7/25
 * @description ：
 * @version: 1.0
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.IdCardUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 统计报表
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

	@Reference
	private MemberService memberService;

	@Reference
	private SetmealService setmealService;

	@Reference
	private ReportService reportService;


	@RequestMapping("/getSetmealReport")
	public Result getSetmealReport(){
		try{
			// 通过service,获取套餐占比
			List<Map<String,Object>> mapList = reportService.findSetmealCount();

			// 封装套餐名称列表
			// 从集合中遍历获取套餐名称
			List<String> setmealNames = new ArrayList<>();
			for (Map<String,Object> mapOne:mapList){
				setmealNames.add(mapOne.get("name").toString());
			}
			// 返回数据,把数据封装到Map
			Map<String,Object> result = new HashMap<>();
			result.put("setmealNames",setmealNames);
			result.put("setmealCount",mapList);
			return new Result(true,MessageConst.ACTION_SUCCESS,result);
		}catch(Exception e){
			e.printStackTrace();
			return new Result(false,MessageConst.ACTION_FAIL);
		}
	}

	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData(){
		try{
		   Map<String,Object> map = reportService.findBusinessData();
		   return new Result(true,MessageConst.ACTION_SUCCESS,map);
		}catch(Exception e){
		    e.printStackTrace();
		    return  new Result(false,MessageConst.ACTION_FAIL);
		}
	}

	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessData(HttpServletResponse response){
		try{
		    // 通过service获取源数据
			Map<String,Object> reportData = reportService.findBusinessData();
			log.debug(">>>>>> reportData:{}",reportData);
			// 把数据写入excel
			// 先读取Excel
			InputStream inputStream = this.getClass().getResourceAsStream("/report_template.xlsx");
			// 构建excel对象
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
			// 读取sheet
			Sheet sheet = xssfWorkbook.getSheetAt(0);
			// 读取Row
			Row row  = sheet.getRow(2);
			// 读取cell
			// 设置报表日期
			row.getCell(5).setCellValue(reportData.get("reportDate").toString());

			// 设置会员相关数据
			row = sheet.getRow(4);
			row.getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
			row.getCell(7).setCellValue((Integer)reportData.get("totalMember"));
			row = sheet.getRow(5);
			row.getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
			row.getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));
			// 设置预约及已到诊数据
			// 设置今日预约及到诊
			row = sheet.getRow(7);
			row.getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
			row.getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
			// 设置本周预约及到诊
			row = sheet.getRow(8);
			row.getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
			row.getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
			// 设置本月预约及到诊
			row = sheet.getRow(9);
			row.getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
			row.getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

			// 设置热门套餐
			int rowNum = 12;
			List<Map<String,Object>> hotSetmealList = (List<Map<String,Object>>)reportData.get("hotSetmeal");
			for(Map<String,Object> oneMap:hotSetmealList){
				String name = (String)oneMap.get("name");
				Long setmealCount = (Long)oneMap.get("setmeal_count");
				BigDecimal proportion = (BigDecimal)oneMap.get("proportion");
				row = sheet.getRow(rowNum);
				row.getCell(4).setCellValue(name);
				row.getCell(5).setCellValue(setmealCount);
				row.getCell(6).setCellValue(proportion.doubleValue());
				rowNum++;
			}
			// 通过流下载excel
			// 获取到客户端流
			ServletOutputStream servletOutputStream = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("content-Disposition","attachment;filename="+reportData.get("reportDate").toString()+"_report.xlsx");
			xssfWorkbook.write(servletOutputStream);
			servletOutputStream.flush();
			servletOutputStream.close();
			xssfWorkbook.close();
			return null;
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}


    /**获取起始日期和结束日期
     * @author ：xym
     * @date ：2019.7.30 10:32
     * @description ：根据时间段统计会员数量
     * @version: 1.0
     */
	@RequestMapping("/getMonthNumber")
	public Result getMonthNumber(@RequestBody Map<String,String> map){

		//用Map集合封装起始日期和结束日期
		String beginDate = map.get("beginDate");
		String endDate = map.get("endDate");

		//起始日期用"-" 切割
		String[] split1 = beginDate.split("-");
		//取出索引为1的 2019-    07
		String s1 = split1[1];
		//将String类型转换为 Integer类型
		int i1 = Integer.parseInt(s1);

		//结束日期用"-" 切割
		String[] split2 = endDate.split("-");
		//取出索引为1的 2019-    07
		String s2 = split2[1];
		//将String类型转换为 Integer类型
		int i2 = Integer.parseInt(s2);

		//打印起始日期和结束日期
		System.out.println(i1);
		System.out.println(i2);

		//定义一个日期格式
		String month="";
		//Calendar calendar =Calendar.getInstance();
		//calendar.get()
		//将12个月份用普通for遍历出来放在集合中
		List<String> monthList = new ArrayList();

		//如果起始日期年份小于和结束日期年份
		if (Integer.parseInt(split1[0])<Integer.parseInt(split2[0])){
			for (int i = 1; i < 13; i++) {
				//month=split1[1]
				//如果起始日期的月份大于等于1切小于等于12
				if (i>=i1&&i<=12){
					//将年份和日期进行拼接字符串 中间用.隔开
				   month=split1[0]+"."+i;
				   //拼接好的字符串放进集合中并打印
				   monthList.add(month);
				   System.out.println(month);
				}
			}
		}
		//如果起始日期年份小于和结束日期年份
		if (Integer.parseInt(split1[0])<Integer.parseInt(split2[0])){
			for (int i = 1; i < 13; i++) {
				//month=split1[1]
				//判断结束日期的月份
				if (i>=0&&i<=i2){
					//将年份和日期进行拼接字符串 中间用.隔开
					month=split2[0]+"."+i;
					//拼接好的字符串放进集合中并打印
					monthList.add(month);
					System.out.println(month);
				}
			}
		}
		//如果起始日期年份等于和结束日期年份
		if (Integer.parseInt(split1[0])==Integer.parseInt(split2[0])){
			for (int i = 1; i < 13; i++) {
				//month=split1[1]
				//判断起始日期结束日期的月份
				if (i>=i1&&i<=i2){
					//将年份和日期进行拼接字符串 中间用.隔开
					month=split1[0]+"."+i;
					//拼接好的字符串放进集合中并打印
					monthList.add(month);
					System.out.println(month);
				}
			}
		}
		try {
			//调用 memberService的findMemberCountByMonth方法
			List<Integer> memberCount = memberService.findMemberCountByMonth(monthList);
            //将日期和会员个数封装到Map
			Map<String,Object> maps	 = new HashMap<>();
			maps.put("months",monthList);
			maps.put("memberCount",memberCount);
			return new Result(true,MessageConst.ACTION_SUCCESS,maps);
		}catch (Exception e){
			e.printStackTrace();
			return new Result(false,MessageConst.ACTION_FAIL);
		}

	}

    /**
     * 获取会员性别占比和会员年龄占比
     *
     * @return
     */
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getMemberReport2")
    public Result getMemberReport() {
        try {
            // 通过service,获取会员性别占比
            List<Map<String, Object>> memberCount = reportService.findAllMemberCount();
            List<String> memberNames = new ArrayList<>();

            // 封装性别名称列表
            // 从集合中遍历获取性别名称
            for (Map<String, Object> map : memberCount) {
                if (map.get("name").toString().equals("1")) {
                    memberNames.add("男");
                    map.put("name", "男");
                } else {
                    memberNames.add("女");
                    map.put("name", "女");
                }
            }
            // 返回数据,把数据封装到Map
            Map<String, List> result = new HashMap<>();
            result.put("memberNames", memberNames);
            result.put("memberCount", memberCount);


            // 通过service,获取会员年龄占比
            //定义空的集合
            List<String> memberAges = new ArrayList<>();
            List<Map<String, Object>> memberAgesCount = new ArrayList<>();
            //获取所有会员的身份证号
            List<String> idCardCount = reportService.findAllMemberAgeCount();
            //初始化存储页面Map年龄和各值的数据
            int age = 0;
            Integer count1 = 0;
            Integer count2 = 0;
            Integer count3 = 0;
            Integer count4 = 0;
            Integer count5 = 0;
            Map<String, Object> onemap1 = new HashMap<>();
            Map<String, Object> onemap2 = new HashMap<>();
            Map<String, Object> onemap3 = new HashMap<>();
            Map<String, Object> onemap4 = new HashMap<>();
            Map<String, Object> onemap5 = new HashMap<>();
            //遍历身份证号，通过IdCardUtils工具类，获取全部会员的年龄
            for (String s : idCardCount) {
                age = IdCardUtils.getAge(s);
                if (age > 0 && age <= 18) {
                    count1++;
                    onemap1.put("value", count1);
                }
                if (age > 18 && age <= 25) {
                    count2++;
                    onemap2.put("value", count2);
                }
                if (age > 25 && age <= 30) {
                    count3++;
                    onemap3.put("value", count3);
                }
                if (age > 30 && age <= 35) {
                    count4++;
                    onemap4.put("value", count4);
                }
                if (age > 35) {
                    count5++;
                    onemap5.put("value", count5);
                }
            }
            //判断 统计的会员年龄段个数，有值的 就返回给页面。
            if (count1 > 0) {
                onemap1.put("name", "0-18岁");
                memberAgesCount.add(onemap1);
            }
            if (count2 > 0) {
                onemap2.put("name", "19-25岁");
                memberAgesCount.add(onemap2);
            }
            if (count3 > 0) {
                onemap3.put("name", "26-30岁");
                memberAgesCount.add(onemap3);
            }
            if (count4 > 0) {
                onemap4.put("name", "31-35岁");
                memberAgesCount.add(onemap4);
            }
            if (count5 > 0) {
                onemap5.put("name", "35岁以上");
                memberAgesCount.add(onemap5);
            }
            // 封装年龄范围列表
            // 从集合中遍历获取年龄范围
            for (Map<String, Object> map : memberAgesCount) {
                memberAges.add(map.get("name").toString());
            }

            // 返回数据,把数据封装到Map
            result.put("memberAges", memberAges);
            result.put("memberAgesCount", memberAgesCount);
            log.debug(">>>>>>>>>>>>result:{}"+result);
            return new Result(true, MessageConst.ACTION_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }


}
